//
//  PhotoShareManager.m
//  PersonalOCTest
//
//  Created by zlf on 2025/6/9.
//

#import "PhotoShareManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <objc/runtime.h> // 添加运行时框架引用


// 为UIImagePickerController添加分类实现回调block
@interface UIImagePickerController (CompletionBlock)

@property (nonatomic, copy) void(^completionBlock)(UIImage *image, NSURL *assetURL);

@end

@implementation UIImagePickerController (CompletionBlock)

- (void)setCompletionBlock:(void (^)(UIImage *, NSURL *))completionBlock {
    objc_setAssociatedObject(self, @selector(completionBlock), completionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(UIImage *, NSURL *))completionBlock {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    PHAsset *asset = info[UIImagePickerControllerPHAsset];
    NSURL *assetURL = [NSURL URLWithString:asset.localIdentifier];
    
    if (self.completionBlock) {
        self.completionBlock(image, assetURL);
    }
}

@end

@implementation PhotoShareManager

+ (void)sharePhotoFromAlbumWithCompletion:(void(^)(BOOL, NSError * _Nullable))completion {
    // 检查相册权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    
    if (status == PHAuthorizationStatusAuthorized) {
        [self presentImagePickerWithCompletion:completion];
    } else if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self presentImagePickerWithCompletion:completion];
                });
            } else {
                NSError *error = [NSError errorWithDomain:@"PhotoShare" code:403 userInfo:@{NSLocalizedDescriptionKey : @"相册权限被拒绝"}];
                completion(NO, error);
            }
        }];
    } else {
        NSError *error = [NSError errorWithDomain:@"PhotoShare" code:403 userInfo:@{NSLocalizedDescriptionKey : @"请前往设置开启相册权限"}];
        completion(NO, error);
    }
}

+ (void)presentImagePickerWithCompletion:(void(^)(BOOL, NSError * _Nullable))completion {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = @[(NSString *)kUTTypeImage];
        
        // Get the topmost visible view controller
        UIViewController *topController = [self topViewController];
        __weak typeof(topController) weakTopController = topController;
        
        picker.completionBlock = ^(UIImage *image, NSURL *assetURL) {
            [weakTopController dismissViewControllerAnimated:YES completion:nil];
            
            if (image) {
                UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[image] applicationActivities:nil];
                activityVC.modalPresentationStyle = UIModalPresentationPopover;
                [weakTopController presentViewController:activityVC animated:YES completion:nil];
                completion(YES, nil);
            } else {
                NSError *error = [NSError errorWithDomain:@"PhotoShare" code:404 userInfo:@{NSLocalizedDescriptionKey : @"未选择图片"}];
                completion(NO, error);
            }
        };
        
        [topController presentViewController:picker animated:YES completion:nil];
    });
    
    
}

// Add this new helper method
+ (UIViewController *)topViewController {
    // 获取当前活跃窗口的现代方法
    UIWindow *keyWindow = nil;
    
    if (@available(iOS 13.0, *)) {
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive && [scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        keyWindow = window;
                        break;
                    }
                }
                
                if (!keyWindow && windowScene.windows.count > 0) {
                    keyWindow = windowScene.windows.firstObject;
                }
                
                break;
            }
        }
    } else {
        keyWindow = [UIApplication sharedApplication].windows.firstObject;
    }
    
    // 如果还是没找到窗口，回退到旧方法
    if (!keyWindow) {
        keyWindow = [UIApplication sharedApplication].windows.firstObject;
    }
    
    UIViewController *rootVC = keyWindow.rootViewController;
    
    UIViewController *topController = rootVC;
    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }
    return topController;
}
@end




